import Common from './common';

export default class {

    static extends = [Common]

    // 当前处理的配置项信息
    currentItem = {}

    // 鼠标点击的时候，距离页面的距离
    mouseRectPos = {}

    // 被点击元素
    startPos = {}

    // 点击元素的真正父节点，因为点击的是toolbar，所以需要获取真正的父元素
    parentNode = null

    // 鼠标按下获取初始信息
    mouseDown = (itemConfig) => {
        return (e) => {
            const pos = this.getElPos(e.target);

            this.currentItem = itemConfig;

            this.mouseRectPos = {
                left: e.pageX,
                top: e.pageY
            };

            this.startPos = pos;

            this.parentNode = e.target.parentNode;

            this.models.page.set({
                selectContainer: this.currentItem
            })

            document.addEventListener('mousemove', this.mouseMove);
            document.addEventListener('mouseup', this.mouseUp);
        }
    }

    // 鼠标抬起删除移动事件
    mouseUp = () => {
        document.removeEventListener('mousemove', this.mouseMove);
        document.removeEventListener('mouseup', this.mouseUp);
    }

    // 移动鼠标
    mouseMove = (e) => {
        const {page} = this.models;
        const [config] = page.get(['config']);
        const pageX = e.pageX;
        const pageY = e.pageY;

        let parentPos = {
            left: 0,
            top: 0
        };

        if (this.parentNode) {
            parentPos = this.getElPos(this.parentNode.offsetParent);
        }

        // 鼠标移动距离
        let distanceTop = pageY - this.mouseRectPos.top;
        let distanceLeft = pageX - this.mouseRectPos.left;

        // 初始位置加上鼠标移动距离，减掉距离父元素的距离就是新距离
        let newTop = this.startPos.top + distanceTop - parentPos.top;
        let newLeft = this.startPos.left + distanceLeft - parentPos.left;

        const newConfig = this.setConfigItem(config, this.currentItem.id, 'position', {
            top: newTop,
            left: newLeft
        });

        page.set({
            config: newConfig
        });
    }
}